package ui.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Bean.GetBankcardBean;
import Bean.TiXianBean;
import Utils.StringUtil;
import base.BaseAct;
import base.BaseBiz;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.ScrollViewFinal;
import coom.Constants;
import event.BankCardEvent;
import event.NetErrorEvent;
import ui.activity.mine.biz.ReturnIncomeBiz;
import ui.activity.mine.component.DaggerReturnIncomeComponent;
import ui.activity.mine.contract.ReturnIncomeContract;
import ui.activity.mine.module.ReturnIncomeModule;
import ui.activity.mine.presenter.ReturnIncomePresenter;
import ui.model.AccountMoneyInfo;
import ui.model.WithDrawInfo;
import util.AlertUtils;
import util.CommonViewUtil;
import util.ToastUtils;
import widget.alertview.AlertView;
import widget.alertview.AlertView1;
import widget.alertview.OnItemClickListener;
import widget.dialog.InputPwdDialog;
import widget.dialog.MyDialog;
import widget.dialog.SetPwdDialog;
import widget.dialog.TiShiDialog;


/**
 * 收益提现
 * Created by chenjian on 2017/8/4.
 */

public class ReturnIncomeAct extends BaseAct implements ReturnIncomeContract.View {


    @Inject
    ReturnIncomePresenter presenter;
    @Inject
    ReturnIncomeBiz biz;

    @BindView(R.id.needsx)
    TextView needsx;
    @BindView(R.id.returnofincome_txt1)
    TextView cardName;
    @BindView(R.id.returnofincome_relati)
    RelativeLayout cardLayout;
    @BindView(R.id.returnofincome_edit)
    EditText input;
    @BindView(R.id.returnofincome_txt2)
    TextView totalMoeny;
    @BindView(R.id.returnofincome_but)
    Button submit;
    @BindView(R.id.return_income_money_limit)
    TextView moneyLimit;
    @BindView(R.id.return_income_money_time)
    TextView moneyTime;
    @BindView(R.id.tixiantimetxt)
    TextView tixiantimetxt;
    @BindView(R.id.return_income_buy)
    TextView buy;
    @BindView(R.id.sv)
    ScrollViewFinal sv;
    @BindView(R.id.ptr_layout)
    PtrClassicFrameLayout ptr;
    boolean isWithDraw = false;


    private TiXianBean mtiXianBean;
    private String bankNum = "";
    private String bankName = "";
    private String bankId = "";
    private String phoneNumber;

    String[] infoStr = {"提现记录"};

    private SharedPreferences sp;

    GetBankcardBean.DataBean.ItemsBean itemsBean;

    String type = "1";
    private InputMethodManager imm;
    EditText etName;//拓展View内容
    //拓展窗口
    AlertView1 mAlertViewExt;
    private SetPwdDialog setPwdDialog;

    private InputPwdDialog inputPwdDialog;
    private TiShiDialog tiShiDialog;

    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        setContentView(R.layout.activity_return_income);
    }

    @Override
    protected void setup() {
        DaggerReturnIncomeComponent.builder().returnIncomeModule(new ReturnIncomeModule(this)).build().inject(this);
        presenter.setBiz(biz);
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        setKeyboard();
        type = StringUtil.isNullOrEmpty(getIntent().getStringExtra(Constants.KEYSTRING)) ? "1" : getIntent().getStringExtra(Constants.KEYSTRING);
        itemsBean = (GetBankcardBean.DataBean.ItemsBean) getIntent().getSerializableExtra(Constants.KEY);
        CommonViewUtil.setDarw(needsx, this, R.mipmap.present_record, -1,
                -1, -1);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.getWithDraw(true);
            }
        });
        ptr.autoRefresh();
        buy.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        buy.getPaint().setAntiAlias(true);//抗锯齿
        if (type.equals("1")) {
            setToolBar("分润提现", "");
            moneyTime.setVisibility(View.INVISIBLE);
        } else if (type.equals("2")) {
            setToolBar("激活提现", "");
            moneyTime.setVisibility(View.INVISIBLE);
        }
        else if (type.equals("10")) {
            setToolBar("拓新提现", "");
            moneyTime.setVisibility(View.INVISIBLE);
        }
        else if (type.equals("11")) {
            setToolBar("成长提现", "");
            moneyTime.setVisibility(View.INVISIBLE);
        }
        else if (type.equals("12")) {
            setToolBar("领导提现", "");
            moneyTime.setVisibility(View.INVISIBLE);
        }

        if (itemsBean != null) {
            cardName.setText(itemsBean.getBank() + "(" + itemsBean.getBankNo().substring(itemsBean.getBankNo().length() - 4, itemsBean.getBankNo().length()) + ")");
            bankNum = itemsBean.getBankNo();
            bankName = itemsBean.getBank();
            bankId = itemsBean.getId();
        }
        RxView.clicks(needsx)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toShowInfo());
        RxView.clicks(cardLayout)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toCardList());
        RxView.clicks(submit)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                            if (isWithDraw) {
                                presenter.getPwdInfo(input.getText().toString().trim(), bankNum, bankId, cardName.getText().toString(), type);
                            }
                        }
                );
        RxView.clicks(buy)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toBuy());

        biz.getWithTixianType(new BaseBiz.Callback<TiXianBean>() {
            @Override
            public void onSuccess(TiXianBean tiXianBean) {
                mtiXianBean = tiXianBean;
                if (!type.equals("4")) {
                    if ((mtiXianBean.getBackStrategy().equals("month") && type.equals("2"))
                            || (mtiXianBean.getDividedStrategy().equals("month") && type.equals("1"))
                            || (mtiXianBean.getBackStrategy().equals("no_setting") && type.equals("2"))
                            || (mtiXianBean.getDividedStrategy().equals("no_setting") && type.equals("1"))) {
                        tixiantimetxt.setText("");
                    }
                }
            }

            @Override
            public void onFailure(TiXianBean tiXianBean) {

            }
        });
    }

    @Override
    public void loadMoreComplete() {
        sv.onLoadMoreComplete();
    }


    @Override
    public void hasLoadMore(boolean b) {
        sv.setHasLoadMore(false);
    }

    @Override
    public void refreshComplete() {
        ptr.onRefreshComplete();
    }

    /**
     * 获取卡信息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerSelectCard(BankCardEvent event) {
        if (event.getBean() != null) {
            cardName.setText(event.getBean().getBank() + "(" + event.getBean().getBankNo().substring(event.getBean().getBankNo().length() - 4,
                    event.getBean().getBankNo().length()) + ")");
            bankNum = event.getBean().getBankNo();
            bankName = event.getBean().getBank();
            bankId = event.getBean().getId();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
            phoneNumber = sp.getString("phonenumber", "");
            presenter.getUserCard();
            presenter.getMoneyInfo();
        } catch (Exception e) {

        }
    }

    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }


    @Override
    public void upDateUI(GetBankcardBean.DataBean.ItemsBean bean) {
        try {
            if (!TextUtils.isEmpty(bean.getBankNo()) && itemsBean == null) {
                if (StringUtil.isNullOrEmpty(bankNum) || StringUtil.isNullOrEmpty(bankName)) {
                    cardName.setText(bean.getBank() + "(" +
                            bean.getBankNo().substring(bean.getBankNo().length() - 4,
                                    bean.getBankNo().length()) + ")");
                    bankNum = bean.getBankNo();
                    bankName = bean.getBank();
                    bankId = bean.getId();
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void upDateMoneyUI(AccountMoneyInfo info) {
        try {
            if (type.equals("1")) {
//                totalMoeny.setText("当前余额 ¥" + StringUtils.getFormatPrice(info.getDividedTotal()));
                Spanned strB = Html.fromHtml("当前余额 ¥" + StringUtil.getFormatPrice(info.getDividedTotal())
                        + "，<font color=#FF2F2F>" + "可提现余额 ¥" + StringUtil.getFormatPrice(info.getDividedAvailableAmount()) + "</font>");
                totalMoeny.setText(strB);
            } else if (type.equals("2")) {
                Spanned strB = Html.fromHtml("当前余额 ¥" + StringUtil.getFormatPrice(info.getReturnTotal())
                        + "，<font color=#FF2F2F>" + "可提现余额 ¥" + StringUtil.getFormatPrice(info.getReturnAvailableAmount()) + "</font>");
                totalMoeny.setText(strB);
            } else if (type.equals("10")) {
                Spanned strB = Html.fromHtml("当前余额 ¥" + StringUtil.getFormatPrice(info.getTx())
                        + "，<font color=#FF2F2F>" + "可提现余额 ¥" + StringUtil.getFormatPrice(info.getTx()) + "</font>");
                totalMoeny.setText(strB);
            }
            else if (type.equals("11")) {
                Spanned strB = Html.fromHtml("当前余额 ¥" + StringUtil.getFormatPrice(info.getCz())
                        + "，<font color=#FF2F2F>" + "可提现余额 ¥" + StringUtil.getFormatPrice(info.getCz()) + "</font>");
                totalMoeny.setText(strB);
            }
            else if (type.equals("12")) {
                Spanned strB = Html.fromHtml("当前余额 ¥" + StringUtil.getFormatPrice(info.getLd())
                        + "，<font color=#FF2F2F>" + "可提现余额 ¥" + StringUtil.getFormatPrice(info.getLd()) + "</font>");
                totalMoeny.setText(strB);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void ShowDialog() {
        AlertView checkAlert = AlertUtils.checkInfo(ReturnIncomeAct.this, new AlertUtils.AlertViewControl() {
            @Override
            public void onItemClickListener(int positions) {
                if (positions == 0) {
                    presenter.toWithDrawList();
                }
            }
        }, "请选择操作", infoStr);
        checkAlert.show();
    }

    @Override
    public void successJump(String money, String cardName) {
        if (inputPwdDialog != null && inputPwdDialog.isShowing()) {
            inputPwdDialog.dismiss();
        }
        Intent intent = new Intent(ReturnIncomeAct.this, ForwardAct.class);
        intent.putExtra("money", money);
        intent.putExtra("card", cardName);
        startActivity(intent);
        finish();
    }


    private void ShowD() {
        AlertView checkAlert = AlertUtils.showInfo(ReturnIncomeAct.this, new AlertUtils.AlertViewControl() {
            @Override
            public void onItemClickListener(int positions) {
                if (positions == 0) {
                    presenter.toWithDraw(sp.getString("id", "0"), input.getText().toString().trim(), bankNum, bankId, cardName.getText().toString(), type);
                }
            }
        }, "提示", "您正在进行提示操作");
        checkAlert.show();
    }

    @Override
    public void showEdit() {
        if (mAlertViewExt == null) {
            String phone = "";
            if (phoneNumber.length() > 4) {
                phone = phoneNumber.substring(phoneNumber.length() - 4, phoneNumber.length());
            } else {
                phone = "登录手机号";
            }
            //拓展窗口
            mAlertViewExt = new AlertView1("短信验证码", "已向您的尾号" + phone + "的手机发送验证码", "取消",
                    null, new String[]{"确定"}, this, AlertView1.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    closeKeyboard();
                    if (position == 0) {
                        if (StringUtil.isNullOrEmpty(etName.getText().toString().trim())) {
                            ToastUtils.shortToast("请输入验证码");
                            return;
                        }
                        presenter.toWithDraw(input.getText().toString().trim(), bankNum, bankId, cardName.getText().toString(), type, etName.getText().toString().trim());

                    }
                    mAlertViewExt.dismiss();
                }
            });
            ViewGroup extView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.alertext_form, null);
            etName = extView.findViewById(R.id.etName);
            etName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean focus) {
                    //输入框出来则往上移动
                    boolean isOpen = imm.isActive();
                    mAlertViewExt.setMarginBottom(isOpen && focus ? 120 : 0);
                }
            });
            mAlertViewExt.addExtView(extView);
        }
        mAlertViewExt.show();
    }

    /**
     * 设置提现验证码
     */

    @Override
    public void showAddPwd() {
        if (setPwdDialog == null) {
            setPwdDialog = new SetPwdDialog(this, "", new MyDialog.DialogCallback() {
                @Override
                public void OnConfirm() {
                    presenter.toAddPwd();
                    if (setPwdDialog != null && setPwdDialog.isShowing()) {
                        setPwdDialog.dismiss();
                    }
                }

                @Override
                public void OnConfirm1() {

                }

                @Override
                public void OnCancel() {

                }
            });
        }
        setPwdDialog.show();

    }

    @Override
    public void showPwd() {
        if (!mtiXianBean.getBackStrategy().equals("now") && !type.equals("4")) {
            if (tiShiDialog == null) {
                tiShiDialog = new TiShiDialog(this, new MyDialog.DialogCallback() {
                    @Override
                    public void OnConfirm() {
                        tiShiDialog.dismiss();
                        showPwdDialog();
                    }

                    @Override
                    public void OnConfirm1() {
                        if (tiShiDialog != null && tiShiDialog.isShowing()) {
                            tiShiDialog.dismiss();
                        }
                    }

                    @Override
                    public void OnCancel() {

                    }
                });
            }
            tiShiDialog.initmoney(input.getText().toString());
            tiShiDialog.show();
        } else {
            showPwdDialog();
        }


    }

    private void showPwdDialog() {
        if (inputPwdDialog == null) {
            inputPwdDialog = new InputPwdDialog(ReturnIncomeAct.this, new MyDialog.DialogCallback() {
                @Override
                public void OnConfirm() {
                    if (StringUtil.isNullOrEmpty(inputPwdDialog.getEditNumber()) || inputPwdDialog.getEditNumber().length() != 6) {
                        showMsg("请输入完整的提现密码");
                        return;
                    }
                    presenter.toWithDraw(input.getText().toString().trim(), bankNum, bankId, cardName.getText().toString(), type, inputPwdDialog.getEditNumber());
                }

                @Override
                public void OnConfirm1() {
                    presenter.toAddPwd();
                    if (inputPwdDialog != null && inputPwdDialog.isShowing()) {
                        inputPwdDialog.dismiss();
                    }
                }

                @Override
                public void OnCancel() {

                }
            });
        }
        inputPwdDialog.show();
        inputPwdDialog.setClearText();
    }

    @Override
    public void setEnable(boolean enable) {
        if (inputPwdDialog != null) {
            inputPwdDialog.setSubmitEnable(true);
        }
    }

    @Override
    public void upDateInfo(WithDrawInfo info) {
        if (type.equals("1")) {
            moneyLimit.setText(info.getTip_devided_amount());
            moneyTime.setVisibility(View.VISIBLE);
            moneyTime.setText(info.getTip_devided_comment());
//            if (info.getTip_get_money_divided_enable().equals("on")) {
                isWithDraw = true;
                submit.setEnabled(true);
                submit.setBackgroundResource(R.drawable.btn_bg_blue);
//            } else {
//                isWithDraw = false;
//                submit.setEnabled(false);
//                submit.setBackgroundResource(R.drawable.btn_bg_9a9a9a);
//            }
        } else if (type.equals("2")) {
            moneyLimit.setText(info.getTip_back_amount());
            moneyTime.setText(info.getTip_back_comment());
            moneyTime.setVisibility(View.VISIBLE);
//            if (info.getTip_get_money_back_enable().equals("on")) {
                isWithDraw = true;
                submit.setEnabled(true);
                submit.setBackgroundResource(R.drawable.btn_bg_blue);
//            } else {
//                isWithDraw = false;
//                submit.setEnabled(false);
//                submit.setBackgroundResource(R.drawable.btn_bg_9a9a9a);
//            }
        }
        else if (type.equals("10")) {
            moneyLimit.setText(info.getTip_tx_amount());
            moneyTime.setText(info.getTip_tx_comment());
            moneyTime.setVisibility(View.VISIBLE);
//            if (info.getTip_get_money_tx_enable().equals("on")) {
                isWithDraw = true;
                submit.setEnabled(true);
                submit.setBackgroundResource(R.drawable.btn_bg_blue);
//            } else {
//                isWithDraw = false;
//                submit.setEnabled(false);
//                submit.setBackgroundResource(R.drawable.btn_bg_9a9a9a);
//            }
        }
        else if (type.equals("11")) {
            moneyLimit.setText(info.getTip_cz_amount());
            moneyTime.setText(info.getTip_cz_comment());
            moneyTime.setVisibility(View.VISIBLE);
//            if (info.getTip_get_money_cz_enable().equals("on")) {
                isWithDraw = true;
                submit.setEnabled(true);
                submit.setBackgroundResource(R.drawable.btn_bg_blue);
//            } else {
//                isWithDraw = false;
//                submit.setEnabled(false);
//                submit.setBackgroundResource(R.drawable.btn_bg_9a9a9a);
//            }
        }
        else if (type.equals("12")) {
            moneyLimit.setText(info.getTip_ld_amount());
            moneyTime.setText(info.getTip_ld_comment());
            moneyTime.setVisibility(View.VISIBLE);
//            if (info.getTip_get_money_ld_enable().equals("on")) {
                isWithDraw = true;
                submit.setEnabled(true);
                submit.setBackgroundResource(R.drawable.btn_bg_blue);
//            } else {
//                isWithDraw = false;
//                submit.setEnabled(false);
//                submit.setBackgroundResource(R.drawable.btn_bg_9a9a9a);
//            }
        }
    }

    private void closeKeyboard() {
        //关闭软键盘
        imm.hideSoftInputFromWindow(etName.getWindowToken(), 0);
        //恢复位置
        mAlertViewExt.setMarginBottom(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mAlertViewExt != null && mAlertViewExt.isShowing()) {
                mAlertViewExt.dismiss();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);

    }
}
